import os
import subprocess
import threading
import time


def kill_exe(exe_name):
    """
    杀死exe进程
    :param exe_name:进程名字
    :return:无
    """
    os.system('taskkill /f /t /im ' + exe_name)


def rtsp_service(mediamtx_path):
    os.chdir(mediamtx_path)

    exe_name = r'E:\streaming\mediamtx_v1.6.0_windows_amd64\mediamtx.exe'
    kill_exe(exe_name)

    time.sleep(3)

    exe_path = r"E:\streaming\mediamtx_v1.6.0_windows_amd64\mediamtx.exe"

    # 启动 mediamtx.exe，通过 stdout 和 stderr 参数将输出重定向到空文件
    subprocess.run([exe_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)

    # 执行完成后会继续这里的代码
    print("server started")


def ffmpeg_service(ffmpeg_path):
    ffmpeg_command = [
        ffmpeg_path,
        '-f', 'dshow',
        '-i', 'video=Integrated Camera',
        '-vcodec', 'libx264',  # 可以尝试其他编码器，如 libx265
        '-preset:v', 'fast',  # 调整预设
        '-tune:v', 'zerolatency',
        '-rtsp_transport', 'udp',  # 使用 UDP 传输协议
        '-f', 'rtsp',
        'rtsp://localhost:8554/live'
    ]

    subprocess.run(ffmpeg_command)


if __name__ == "__main__":
    # # 设置 DOS 窗口编码为 UTF-8
    os.system('chcp 65001')

    ffmpeg_path = r"E:\ffmpeg-6.1-essentials_build\bin\ffmpeg.exe"
    mp4_path = 'C:\\Users\\hongz\\Desktop\\abc\\video_ornament_yangjian.mp4'

    # 创建线程
    rtsp_thread = threading.Thread(target=rtsp_service, args=('E:\streaming\mediamtx_v1.6.0_windows_amd64',))

    # 启动线程
    rtsp_thread.start()
    time.sleep(2)
    # 调用另一个函数
    ffmpeg_service(ffmpeg_path)

    # 主线程等待所有线程结束
    rtsp_thread.join()

    print("All services have completed.")
